/**
 * @author trex279
 */
var redditJson = {};
var modifiedJson = {};
var fileName = "messages.json";
var newReplies = new Array();

function checkMessages(){
	$.getJSON("http://www.reddit.com/message/inbox/.json",
    	function(data){
			if (data == "") {
				thisApplication.nativeWin.dispatchEvent(loadingErrorEvent);
				return;
			}
	      	redditJson = modifiedJson = data;

			var jsonFromFile = readJsonFromFile(fileName);
			if(jsonFromFile==-1){
				//alert("File size 0");
				storeJson(redditJson,fileName);
				jsonFromFile = readJsonFromFile(fileName);
			}
			
			var oldJson = $.evalJSON(jsonFromFile);
			
			var noNewReplies = compareJson(oldJson, redditJson);	//was written before I realised that the json itself contains information on whether the message is new or not. Still can be used to see if a message has been locally read or not.
			
			showMessages();
			
			if(noNewReplies>0){
				injectContentFunction = function(documentRef){
					documentRef.getElementById("noReplies").innerHTML = noNewReplies;
				}
				thisApplication.showNotification("new_message.html",injectContentFunction);
			}
			else{
				//alert("Nothing new");
			}
			
			storeJson(redditJson, fileName);
		}
	)
};

//noNewReplies
//template = "notify.html"


function showMessages(){
	var commentHtml = "";
	
	var commentsArray = new Array();
	commentsArray = modifiedJson.data.children;
	var unread = "";
	
	for(var i = 0; i<commentsArray.length; i++){
		unread = (commentsArray[i].data.unread == "true")?"unread":"read";
		var createDate = new Date();
		createDate.setTime(commentsArray[i].data.created_utc*1000);
		
		commentHtml+=""+
		"<div class='"+unread+" message'>"+
			"<p class='tagline'>"+
				"<span class='head'>from&nbsp;<b><a class='author' href='http://www.reddit.com/user/"+commentsArray[i].data.author+"'>"+commentsArray[i].data.author+"</a></b>&nbsp;at&nbsp;"+createDate.toLocaleString()+"</span>"+ //need to convert time to time difference
			"</p>"+
			"<p class='subject'>Subject: "+commentsArray[i].data.subject+"</p>"+
			"<div class='body'>"+
				toHtml(commentsArray[i].data.body_html)+
			"</div>"+
			"<ul class='flat-list buttons'>"+
				"<li><a rel='nofollow' class='bylink' href='http://www.reddit.com/"+commentsArray[i].data.context+"'>context</a>"+
				"</li>"+
			"</ul>"+
		"</div><hr />";
	}
	
	$("#messageTab #messages").html(commentHtml);
	thisApplication.nativeWin.dispatchEvent(loadingCompleteEvent);
}

function compareJson(oldJson, newJson){
	var noNewReplies = 0;
	
	var lastMessageId = oldJson.data.children[0].data.name;
	
	var i = 0;
	while(i<newJson.data.children.length && newJson.data.children[i].data.name!=lastMessageId){
		modifiedJson.data.children[i].data.unread="true";
		i++;
		noNewReplies++;
	}
	
	while(newJson.data.children[i]){
		modifiedJson.data.children[i].data.unread="false";
		i++;
	}
	
	storeJson(modifiedJson, "modifiedJson.json");

	return noNewReplies;
}